import axios from 'axios'

import { getToken } from './auth'

const request = axios.create({
    baseURL: "https://sapi.jiangdaye.cn/",
    timeout: 15000,
})

request.interceptors.request.use(function (config) {
    if (getToken()) {
        config.headers.Authorization = "Bearer " + getToken()
    }
    return config
},
    function (error) {
        return Promise.reject(error)
    }
)

request.interceptors.response.use(function (response) {
    return response.data;
}, function (error) {
    if (error.code === "ERR_NETWORK") {
        alert('本次请求超时')
        return
    }
    if (error.response.status === 401) {
        window.location.href = '/login'
        return
    }
    if (error.response.status === 429) {
        window.location.href = '/login'
        return
    }

    console.log(error)

    return Promise.reject(error)
})

export default request